package finalcode;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import javax.swing.JOptionPane;

public class StreamingServer implements Runnable {
	static String list;
	/**
	 * Accept this many connections.
	 */

	/**
	 * The server socket.
	 */
	private ServerSocket my_serverSocket;
	
	public static int port;

	/**
	 * Create the server socket.
	 * 
	 * @param a_port
	 *            the port that the server socket should listen on.
	 */
	public StreamingServer(int a_port) {
		try {
			my_serverSocket = new ServerSocket(a_port);
			System.out.println(my_serverSocket.getLocalPort());
			port = my_serverSocket.getLocalPort();
			System.out.println("STREAMING on "+port);
		} catch (final IOException ioe) {
			System.out.println("Already streaming");
		} catch (final SecurityException se) {
			se.printStackTrace();
		}
	}

	/**
	 * Method that listens on the server socket until close. Responds to to requests for files
	 *  and control commands
	 */

	@Override
	public void run() {
		while (true) {
			try {
				final Socket socket = my_serverSocket.accept();
				final BufferedReader in = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				final String line = in.readLine();
				System.out.println(line);
				final PrintWriter out = new PrintWriter(
						socket.getOutputStream(), true);
				out.println("now streaming");
			} catch (final IOException ioe) {
				System.out.println("Already streaming");
			} catch (final SecurityException se) {
				se.printStackTrace();
			}
		}
	}
	
}
